{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9ac382de-ad26-486b-8b4c-2fe036c9c82c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "822407b0-ca66-4379-84ae-702ad4b0379f",
   "metadata": {},
   "outputs": [],
   "source": [
    "train=pd.read_csv('train.csv')\n",
    "test=pd.read_csv('test.csv')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "defc67a8-9361-4635-a9f3-988ee920774d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "% of women who survived: 0.7420382165605095\n"
     ]
    }
   ],
   "source": [
    "# 取出表格中的两列，性别和存活率构建一个新的数据集women\n",
    "women = train.loc[train.Sex == 'female'][\"Survived\"]\n",
    "\n",
    "# 一共有314条女性记录，由于存活的情况是1，所以累加所有存活特征，就能得到存活数量\n",
    "# 再用存活数量/女性总数得到女性存活率\n",
    "\n",
    "rate_women = sum(women)/len(women)\n",
    "print(\"% of women who survived:\", rate_women)\n",
    "# 获得女性的存活率\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "44676038-3432-42c1-bb00-68add0746847",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "% of men who survived: 0.18890814558058924\n"
     ]
    }
   ],
   "source": [
    "men = train.loc[train.Sex == 'male'][\"Survived\"]\n",
    "rate_men = sum(men)/len(men)\n",
    "\n",
    "print(\"% of men who survived:\", rate_men)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "f6b26aa3-f84b-48f6-a2e5-b569cee978fa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>PassengerId</th>\n",
       "      <th>Survived</th>\n",
       "      <th>Pclass</th>\n",
       "      <th>Name</th>\n",
       "      <th>Sex</th>\n",
       "      <th>Age</th>\n",
       "      <th>SibSp</th>\n",
       "      <th>Parch</th>\n",
       "      <th>Ticket</th>\n",
       "      <th>Fare</th>\n",
       "      <th>Cabin</th>\n",
       "      <th>Embarked</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>Braund, Mr. Owen Harris</td>\n",
       "      <td>male</td>\n",
       "      <td>22.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>A/5 21171</td>\n",
       "      <td>7.2500</td>\n",
       "      <td>NaN</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>Cumings, Mrs. John Bradley (Florence Briggs Th...</td>\n",
       "      <td>female</td>\n",
       "      <td>38.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>PC 17599</td>\n",
       "      <td>71.2833</td>\n",
       "      <td>C85</td>\n",
       "      <td>C</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3</td>\n",
       "      <td>1</td>\n",
       "      <td>3</td>\n",
       "      <td>Heikkinen, Miss. Laina</td>\n",
       "      <td>female</td>\n",
       "      <td>26.0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>STON/O2. 3101282</td>\n",
       "      <td>7.9250</td>\n",
       "      <td>NaN</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>4</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>Futrelle, Mrs. Jacques Heath (Lily May Peel)</td>\n",
       "      <td>female</td>\n",
       "      <td>35.0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>113803</td>\n",
       "      <td>53.1000</td>\n",
       "      <td>C123</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>5</td>\n",
       "      <td>0</td>\n",
       "      <td>3</td>\n",
       "      <td>Allen, Mr. William Henry</td>\n",
       "      <td>male</td>\n",
       "      <td>35.0</td>\n",
       "      <td>0</td>\n",
       "      <td>0</td>\n",
       "      <td>373450</td>\n",
       "      <td>8.0500</td>\n",
       "      <td>NaN</td>\n",
       "      <td>S</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   PassengerId  Survived  Pclass  \\\n",
       "0            1         0       3   \n",
       "1            2         1       1   \n",
       "2            3         1       3   \n",
       "3            4         1       1   \n",
       "4            5         0       3   \n",
       "\n",
       "                                                Name     Sex   Age  SibSp  \\\n",
       "0                            Braund, Mr. Owen Harris    male  22.0      1   \n",
       "1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   \n",
       "2                             Heikkinen, Miss. Laina  female  26.0      0   \n",
       "3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0      1   \n",
       "4                           Allen, Mr. William Henry    male  35.0      0   \n",
       "\n",
       "   Parch            Ticket     Fare Cabin Embarked  \n",
       "0      0         A/5 21171   7.2500   NaN        S  \n",
       "1      0          PC 17599  71.2833   C85        C  \n",
       "2      0  STON/O2. 3101282   7.9250   NaN        S  \n",
       "3      0            113803  53.1000  C123        S  \n",
       "4      0            373450   8.0500   NaN        S  "
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "3632a447-cd25-4f73-a245-49893ce92005",
   "metadata": {},
   "outputs": [],
   "source": [
    "# from sklearn.ensemble import RandomForestRegressor\n",
    "# ages = train[['Age', 'Pclass','Sex']]\n",
    "# ages=pd.get_dummies(ages)\n",
    "# known_ages = ages[ages.Age.notnull()].values\n",
    "# unknown_ages = ages[ages.Age.isnull()].values\n",
    "# y = known_ages[:, 0]\n",
    "# X = known_ages[:, 1:]\n",
    "# rfr = RandomForestRegressor(random_state=60, n_estimators=100, n_jobs=-1)\n",
    "# rfr.fit(X, y)\n",
    "# pre_ages = rfr.predict(unknown_ages[:, 1::])\n",
    "# train.loc[ (train.Age.isnull()), 'Age' ] = pre_ages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "c2097017-d19b-4983-adab-898f0807ae5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# from sklearn.ensemble import RandomForestRegressor\n",
    "# ages = test[['Age', 'Pclass','Sex']]\n",
    "# ages=pd.get_dummies(ages)\n",
    "# known_ages = ages[ages.Age.notnull()].values\n",
    "# unknown_ages = ages[ages.Age.isnull()].values\n",
    "# y = known_ages[:, 0]\n",
    "# X = known_ages[:, 1:]\n",
    "# rfr = RandomForestRegressor(random_state=60, n_estimators=100, n_jobs=-1)\n",
    "# rfr.fit(X, y)\n",
    "# pre_ages = rfr.predict(unknown_ages[:, 1::])\n",
    "# test.loc[ (test.Age.isnull()), 'Age' ] = pre_ages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "c2e9976d-7a41-47b9-a68a-862ade15acdc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 418 entries, 0 to 417\n",
      "Data columns (total 11 columns):\n",
      " #   Column       Non-Null Count  Dtype  \n",
      "---  ------       --------------  -----  \n",
      " 0   PassengerId  418 non-null    int64  \n",
      " 1   Pclass       418 non-null    int64  \n",
      " 2   Name         418 non-null    object \n",
      " 3   Sex          418 non-null    object \n",
      " 4   Age          418 non-null    float64\n",
      " 5   SibSp        418 non-null    int64  \n",
      " 6   Parch        418 non-null    int64  \n",
      " 7   Ticket       418 non-null    object \n",
      " 8   Fare         418 non-null    float64\n",
      " 9   Cabin        418 non-null    object \n",
      " 10  Embarked     418 non-null    object \n",
      "dtypes: float64(2), int64(4), object(5)\n",
      "memory usage: 36.1+ KB\n"
     ]
    }
   ],
   "source": [
    "# train['Age']=train['Age'].astype('int')\n",
    "# train.loc[ (train.Embarked.isnull()), 'Embarked'] = 'C'\n",
    "# train['Cabin'] = train['Cabin'].fillna('U')\n",
    "# train['Cabin']= train['Cabin'].str.get(0)\n",
    "# test['Cabin'] = train['Cabin'].fillna('U')\n",
    "# test['Cabin']= train['Cabin'].str.get(0)\n",
    "test.info()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "00d3f16e-3e84-4dac-9a31-f3aaa09c25c1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "3a1c28b4-3557-42a3-a3f9-5ad53f25835b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8260381593714927\n"
     ]
    }
   ],
   "source": [
    "from sklearn.ensemble import RandomForestClassifier\n",
    "\n",
    "y = train[\"Survived\"]\n",
    "\n",
    "features = [\"Pclass\", \"Sex\", \"SibSp\", \"Parch\",\"Embarked\",\"Cabin\"]\n",
    "X = pd.get_dummies(train[features])\n",
    "X_test = pd.get_dummies(test[features])\n",
    "\n",
    "model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)\n",
    "model.fit(X, y)\n",
    "predictions = model.predict(X_test)\n",
    "score=model.score(X, y)\n",
    "print(score)\n",
    "output = pd.DataFrame({'PassengerId': test.PassengerId, 'Survived': predictions})\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "9ddb565b-a415-4004-a4d5-c8271e46f5ff",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     Pclass  SibSp  Parch  Sex_female  Sex_male\n",
      "0         3      1      0       False      True\n",
      "1         1      1      0        True     False\n",
      "2         3      0      0        True     False\n",
      "3         1      1      0        True     False\n",
      "4         3      0      0       False      True\n",
      "..      ...    ...    ...         ...       ...\n",
      "886       2      0      0       False      True\n",
      "887       1      0      0        True     False\n",
      "888       3      1      2        True     False\n",
      "889       1      0      0       False      True\n",
      "890       3      0      0       False      True\n",
      "\n",
      "[891 rows x 5 columns]\n"
     ]
    }
   ],
   "source": [
    "print(X)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "452a5b2d-964c-42e1-b78e-ff98ab9464b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     PassengerId  Survived\n",
      "0            892         0\n",
      "1            893         1\n",
      "2            894         0\n",
      "3            895         0\n",
      "4            896         1\n",
      "..           ...       ...\n",
      "413         1305         0\n",
      "414         1306         1\n",
      "415         1307         0\n",
      "416         1308         0\n",
      "417         1309         0\n",
      "\n",
      "[418 rows x 2 columns]\n"
     ]
    }
   ],
   "source": [
    "print(output)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "105a2e3f-cd57-4f41-b97a-b3e8aa50c2e2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your submission was successfully saved!\n"
     ]
    }
   ],
   "source": [
    "output.to_csv('submission82.csv', index=False)\n",
    "print(\"Your submission was successfully saved!\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3cff313d-824b-443f-a5ae-0f4a94027078",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
